import React from 'react';
import { Table, Input, Button, Popconfirm, Form, Select } from 'antd';


class EditableTable extends React.Component {
	constructor(props) {
		super(props);
		this.columns = [
			{
				title: 'name',
				dataIndex: 'name',
				width: '30%',
				editable: true
			},
			{
				title: 'age',
				dataIndex: 'age'
			},
			{
				title: 'address',
				dataIndex: 'address'
			},
			{
				title: 'operation',
				dataIndex: 'operation',
				render: (text, record) =>
					this.state.dataSource.length >= 1 ? (
						<Popconfirm
							title="Sure to delete?"
							onConfirm={() => this.handleDelete(record.key)}
						>
							<a>Delete</a>
						</Popconfirm>
					) : null
			}
		];

		this.state = {
			editStatus: false,
			dataSource: [
				{
					key: '0',
					name: 'name 1',
					age: '32 - 1',
					address: 'London, Park Lane no. 0',
					editProps: {
						name: 'input',
						address: 'select'
					},
					selectData: [1, 2, 3, 4]
				},
				{
					key: '1',
					name: 'name 2',
					age: '32 - 2',
					address: 'London, Park Lane no. 1',
					editProps: {
						name: 'input',
						age: 'input'
					}
				}
			],
			count: 2
		};
	}

	handleDelete = key => {
		const dataSource = [...this.state.dataSource];
		this.setState({
			dataSource: dataSource.filter(item => item.key !== key)
		});
	};

	handleAdd = () => {
		const { count, dataSource } = this.state;
		const newData = {
			key: count,
			name: `Edward King ${count}`,
			age: 32,
			address: `London, Park Lane no. ${count}`
		};
		this.setState({
			dataSource: [...dataSource, newData],
			count: count + 1
		});
	};

	onSave = () => {
		this.props.form.validateFields((err, fieldsValue) => {
			if (err) {
				return;
			}

			let dataSource = this.state.dataSource;

			Object.keys(fieldsValue).map(fieldsItem => {
				let pos = fieldsItem.split(',');
				dataSource[pos[1]][pos[0]] = fieldsValue[fieldsItem];
			});

			console.log('editTable2: ', fieldsValue);
			console.log('modifyDataSource: ', dataSource);

			this.setState({ editStatus: false })
		});
	};

	handleInputSave = (e) => {
		console.log(e);
		let newData = [...this.state.dataSource];
		let fieldName = e.currentTarget.dataset.fieldName;
		this.props.form.validateFields((err, fieldsValue) => {
			if (err) {return};

			let fieldPos = fieldName.split(',');
			let value = fieldsValue[fieldName];
			let oldRow = newData[fieldPos[1]];

			newData.splice(fieldPos[1], 1, {
				...oldRow,
				operation: 'new-inp: ' + value
			});
			this.setState({ dataSource: newData })
		})
	};
	handleSelectSave = (value, option) => {
		let newData = [...this.state.dataSource];
		let fieldName = option.props.fieldName;
		let fieldPos = fieldName.split(',');
		let oldRow = newData[fieldPos[1]];

		newData.splice(fieldPos[1], 1, {
			...oldRow,
			operation: 'new-sel: ' + value
		});
		this.setState({ dataSource: newData })
	};

	onEdit = () => {
		this.setState({ editStatus: true })
	};

	render() {
		const { dataSource, editStatus } = this.state;
		let { form } = this.props;

		function renderForm(that, record, dataIndex, fieldName) {
			if (record.editProps[dataIndex] === 'input') {
				return (
					<Input
						data-field-name={fieldName}
						onBlur={that.handleInputSave}
						// onPressEnter={that.save}
						// onBlur={that.save}
					/>
				);
			} else if (record.editProps[dataIndex] === 'select') {
				return (
					<Select
						data-field-name={fieldName}
						onSelect={that.handleSelectSave}
					>
						{record.selectData.map((item, index) => {
							return (
								<Select.Option
									key={dataIndex + index}
									value={item}
									fieldName={fieldName}
								>{item}</Select.Option>
							);
						})}
					</Select>
				);
			}
		}

		const columns = this.columns.map(col => {
			return {
				...col,
				render: (text, record, index) => {
					if ((record.editProps || {})[col.dataIndex] && editStatus) {
						let fieldName = `${col.dataIndex},${index}`;
						return (
							<Form.Item style={{ margin: 0 }}>
								{form.getFieldDecorator(fieldName, {
									rules: [
										{
											required: true,
											message: `${col.title} 必填！`
										}
									],
									initialValue: record[col.dataIndex]
								})(renderForm(this, record, col.dataIndex, fieldName))}
							</Form.Item>
						);
					} else {
						return (
							<div
								className=""
								style={{ paddingRight: 24 }}
							>
								{text}
							</div>
						);
					}
				}
			};
		});
		return (
			<div>
				<Button
					onClick={this.handleAdd}
					type="primary"
					style={{ marginBottom: 16 }}
				>
					Add a row
				</Button>
				<Button
					onClick={editStatus? this.onSave: this.onEdit}
					type="primary"
					style={{ marginBottom: 16 }}
				>
					{editStatus? '保存': '编辑'}
				</Button>

				<Table
					rowClassName={() => 'editable-row'}
					bordered
					dataSource={dataSource}
					columns={columns}
				/>
			</div>
		);
	}
}

EditableTable = Form.create({
	onValuesChange: function (props, changeValues, allValues) {
		console.groupCollapsed('FormOption - onValuesChange:')
		console.log('props: ', props);
		console.log('changeValues: ', changeValues);
		console.log('allValues: ', allValues);
		console.groupEnd();
	}
})(EditableTable);
export { EditableTable as default } ;
